package com.sinocare.project.maintenance.realm;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sinocare.project.common.entity.SccRole;
import com.sinocare.project.common.entity.SncUserLogin;
import com.sinocare.project.maintenance.service.SncUserLoginService;
import com.sinocare.project.maintenance.service.impl.SncUserLoginServiceImpl;
import com.sinocare.project.maintenance.util.ApplicationContextUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

public class MyRealm extends AuthorizingRealm {

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权的方法!");
        String username=(String)principalCollection.getPrimaryPrincipal();//获取账号
        //新建SimpleAuthorizationInfo对象
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //TODO:根据用户名查询用户角色
        SncUserLoginService service = (SncUserLoginService) ApplicationContextUtils.getBean("sncUserLoginService");
        QueryWrapper<Object> wrapper = new QueryWrapper<>();
        wrapper.eq("c.count",username);
        SccRole byUserId = service.getByUserId(wrapper);
        info.addRole(byUserId.getRoleName());
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证的方法!");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        if (username==null){
            return new SimpleAuthenticationInfo();
        }
        //TODO:根据用户名查询用户信息
        SncUserLoginService service = (SncUserLoginService) ApplicationContextUtils.getBean("sncUserLoginService");
        QueryWrapper<SncUserLogin> wrapper = new QueryWrapper<>();
        wrapper.eq("count",username);
        wrapper.eq("status",1);
        SncUserLogin sncUserLogin = service.getOne(wrapper);
        if (sncUserLogin == null) {
            return new SimpleAuthenticationInfo();
        }
        String[] split = sncUserLogin.getPassword().split(",");
        return new SimpleAuthenticationInfo(username, split[0], this.getName());
    }

    /**
     * 设置自定义认证加密方式
     *
     * @param credentialsMatcher 默认加密方式
     */
    @Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        //自定义认证加密方式
        CustomCredentialsMatcher customCredentialsMatcher = new CustomCredentialsMatcher();
        // 设置自定义认证加密方式
        super.setCredentialsMatcher(customCredentialsMatcher);
    }

}
